<template>
  <div>
    <van-nav-bar
      title="注册"
      left-text="返回"
      left-arrow
      @click-left="$router.replace('/')"
    />
    <van-form @submit="register">
      <van-field name="uploader" label="头像">
        <template #input>
          <van-uploader v-model="fileList" :after-read="afterRead" />
        </template>
      </van-field>
      <van-field
        v-model="regForm.nickname"
        name="昵称"
        label="昵称"
        placeholder="昵称"
        :rules="[{ validator: testNickname, message: '昵称已存在' }]"
      />

      <van-field
        v-model="regForm.phone"
        center
        maxlength="11"
        clearable
        label="手机号"
        placeholder="请输入手机号"
        :formatter="numFormatter"
        :rules="[{ pattern, message: '请输入正确的手机号' }]"
      >
        <template #button>
          <van-button
            native-type="button"
            size="small"
            v-if="isSend"
            type="primary"
            @click="sendSms"
            :disabled="isSmsLoad"
            >发送验证码</van-button
          >
          <van-button size="small" v-if="!isSend" type="primary" disabled>{{
            time
          }}</van-button>
        </template>
      </van-field>

      <van-field
        v-model="regForm.smsCode"
        name="短信验证码"
        label="短信验证码"
        placeholder="短信验证码"
        :formatter="trimFormatter"
        :rules="[{ required: true, message: '请填写短信验证码' }]"
      />

      <van-field
        v-model="regForm.password"
        type="password"
        name="密码"
        label="密码"
        placeholder="密码"
        :formatter="trimFormatter"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <van-field
        v-model="regForm.confirmPassword"
        type="password"
        name="确认密码"
        label="确认密码"
        placeholder="确认密码"
        :formatter="trimFormatter"
        :rules="[{ required: true, message: '请填写密码' }]"
      />

      <van-field
        clickable
        name="picker"
        :value="pickerValue"
        label="专业班级"
        placeholder="点击选择专业班级"
        :rules="[{ required: true, message: '请选择专业' }]"
        @click="showPicker = true"
      />
      <van-popup v-model="showPicker" position="bottom">
        <van-picker
          show-toolbar
          value-key="configValue"
          :columns="majorList"
          @cancel="showPicker = false"
          @confirm="pickerConfirm"
        />
      </van-popup>
      <div style="margin: 16px">
        <van-button
          round
          block
          type="info"
          native-type="submit"
          :disabled="isUpload"
          >注册</van-button
        >
      </div>
    </van-form>
  </div>
</template>
<script>
import { Dialog, Toast } from "vant";
import { Notify } from "vant";

export default {
  name: "RegisterPage",
  data() {
    return {
      isSmsLoad: false,
      isSend: true,
      isUpload: false,
      regForm: {
        majorCode: "",
        phone: "",
        nickname: "",
        password: "",
        confirmPassword: "",
        smsCode: "",
        avatar: "",
      },
      fileList: [],
      pickerValue: "",
      showPicker: false,
      isRepeat: false,
      majorList: [],
      time: 60,
      pattern: /^[1][3,4,5,6,7,8,9][0-9]{9}$/,
    };
  },
  methods: {
    trimFormatter(value) {
      return value.replace(" ", "");
    },
    register() {
      this.isUpload = true;
      let message = "";
      let isError = false;
      if (this.regForm.nickname == "") {
        isError = true;
        message = "请输入昵称";
      }
      if (this.regForm.password != this.regForm.confirmPassword) {
        isError = true;
        message = "两次密码不同！";
        this.regForm.confirmPassword = "";
      }
      if (isError) {
        Dialog.alert({
          message: message,
        });
      }

      this.postRequest("/user/reg", this.regForm).then((result) => {
        this.isLogin = false;
        if (result.data.status == 200) {
          localStorage.setItem("loginUser", JSON.stringify(result.data.data));
          localStorage.setItem("tokenName", result.data.data.tokenName);
          localStorage.setItem("tokenValue", result.data.data.tokenValue);
          Notify({ type: "success", message: "注册成功" });
          this.$router.replace("/index");
        } else {
          Notify({ type: "eorror", message: "注册失败" });
        }
        this.isUpload = false;
      });
    },
    sendSms() {
      if (!this.pattern.test(this.regForm.phone)) {
        this.$dialog.alert({
          message: "请输入正确的手机号",
        });
        return;
      }
      this.isSmsLoad = true;
      this.getRequest(`/user/sendSmsCode/${this.regForm.phone}`).then((res) => {
        if (res.data.status == 200) {
          Toast(res.data.msg);
          localStorage.setItem("smsTime", new Date().getTime());
          this.timeDown();
        }
        this.isSmsLoad = false;
      });
    },
    timeDown() {
      let vm = this;
      vm.isSend = false;

      vm.timer = window.setInterval(() => {
        vm.time--;
        if (vm.time <= 0) {
          vm.isSend = true;
          vm.time = 60;
          clearInterval(vm.timer);
          vm.timer = null;
          localStorage.removeItem("smsTime");
        }
      }, 1000);
    },
    testNickname() {
      return new Promise((reslove) => {
        this.getRequest("/user/verifyNickname", {
          nickname: this.regForm.nickname,
        }).then((result) => {
          reslove(result.data.data);
        });
      });
    },
    listMajorConfig() {
      this.getRequest("/config/listChildByParentConfigName", {
        configName: this.CONFIG.MAJOR_CODE,
      }).then((res) => {
        this.majorList = res.data.data;
      });
    },
    pickerConfirm(value) {
      this.pickerValue = value.configValue;
      this.regForm.majorCode = value.configName;
      this.showPicker = false;
    },
    initTimer() {
      let smsTime = +localStorage.getItem("smsTime");
      if (!smsTime) {
        return;
      }
      if (new Date().getTime() > smsTime + 60 * 1000) {
        localStorage.removeItem("smsTime");
        return;
      }
      this.time = (new Date().getTime() - smsTime) / 1000;
      this.time = Math.floor(60 - this.time);
      this.timeDown();
    },
    numFormatter(value) {
      // 过滤输入的数字
      return value.replace(/[^\d]/g, "");
    },
    afterRead(file) {
      this.isUpload = true;
      file.status = "uploading";
      file.message = "上传中...";
      this.uploadFileRequest("/user/uploadAvatar", file).then((result) => {
        if (result && result.status == 200) {
          file.status = "";
          file.message = "";
          file.url = result.data.data;
          this.regForm.avatar = result.data.data;
        } else {
          file.status = "failed";
          file.message = "上传失败";
        }
        this.isUpload = false;
      });
    },
  },
  created() {
    this.listMajorConfig();
    this.initTimer();
  },
};
</script>
